<?php
/**
 * Created by PhpStorm.
 * User: zhao shou qiang
 * Date: 2018/1/09
 * Time: 11:50
 */

namespace backend\controllers;


use common\models\PackageInitiationIncome;
use common\models\PackageUpdateLog;
use Yii;
use yii\db\Exception;
use common\models\Responses;

class PackageInitationIncomeController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();
    }


    /**
     * 团队收益分配
     * @return string
     */
    public function actionBaseTab()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $package_id = (int)Yii::$app->request->get('package_id');
            $type = (int)Yii::$app->request->get('type');

            $model = new PackageInitiationIncome();
            $list = $model->getList(['package_id' => $package_id]);
            //切换编辑页面
            if ($type == 1) {
                $str = $this->renderPartial('@app/views/package/investigation/group-income-eidt.php', ['list' => $list]);
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                return Responses::response200($str, 1, '切换成功');

                //切换只读页面
            } elseif ($type == 2) {
                $str = $this->renderPartial('@app/views/package/investigation/group-income.php', ['list' => $list]);
                return Responses::response200($str, 1, '取消成功');
            }
        }
    }

    /**
     * 删除
     * @return array
     */
    public function actionDelete()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $package_id = (int)Yii::$app->request->post('package_id');
            $id = (int)Yii::$app->request->post('id');

            $model = PackageInitiationIncome::find()->where(['id' => $id, 'package_id' => $package_id])->one();
            if ($model === null) {
                return Responses::response400('该数据不存在', true);
            }

            $initationIncome = new PackageInitiationIncome();
            $transaction = Yii::$app->db->beginTransaction();
            try {

                //TODO 团队收益分配删除记录
                $res = $initationIncome->setUpdateLog($id, $package_id, array(), $userId, PackageUpdateLog::MODULE_INCOME_DISTRIBUTION, 3);
                if (!$res['state']) {
                    throw new Exception($res['msg']);
                }

                $re = $model->delete();
                if ($re) {
                    $transaction->commit();

                    $list = (new PackageInitiationIncome())->getList(['package_id' => $package_id]);
                    $str = $this->renderPartial('@app/views/package/investigation/group-income-eidt.php', ['list' => $list]);
                    //---编辑资产包-发送消息--fly---
                    PackageController::actionPostMessage($package_id);
                    //---编辑资产包-发送消息--fly---
                    return Responses::response200($str, 1, '删除成功');
                } else {
                    throw new \Exception('删除失败');
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 保存多条
     * @return array
     */
    public function actionSaves()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $data = Yii::$app->request->post('PackageInitiationIncome');
            $package_id = (int)Yii::$app->request->get('package_id');
            $transaction = Yii::$app->db->beginTransaction();
            $status = false;
            try {
                if (count($data['id']) > 0) {
                    $packageInitiationIncome = new PackageInitiationIncome();
                    for ($i = 0; $i < count($data['id']); $i++) {
                        //修改
                        if ($data['id'][$i] != '') {
                            $model = PackageInitiationIncome::find()->where(['package_id' => $package_id, 'id' => $data['id'][$i]])->one();
                            $state = false;
                            $changedAttributes = array();
                            if ($model->stage != $data['stage'][$i]) {
                                $model->stage = $data['stage'][$i];
                                $changedAttributes['stage'] = $data['stage'][$i];
                                $state = true;
                            }

                            if ($model->profit != $data['profit'][$i]) {
                                $model->profit = $data['profit'][$i];
                                $changedAttributes['profit'] = $data['profit'][$i];
                                $state = true;
                            }

                            if ($state === false) {
                                continue;
                            }

                            //TODO 添加团队收益分配更新记录
                            $res = $packageInitiationIncome->setUpdateLog($model->id, $package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_INCOME_DISTRIBUTION, 2);
                            if (!$res['state']) {
                                throw new \Exception($res['msg']);
                            }

                            if (!$model->save()) {
                                $error = $model->getFirstErrors();
                                $message = '';
                                if (!empty($error)) {
                                    foreach ($error as $value) {
                                        $message .= $value;
                                    }
                                    $tmpStr = strip_tags($message);
                                    $tmpLen = mb_strlen($tmpStr);
                                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                }
                                throw new Exception("第" . ($i + 1) . "行保存失败，失败原因：{$message}");
                            } else {
                                $status = true;
                            }

                        //新增
                        } else {
                            $model = clone $packageInitiationIncome;
                            $model->package_id = $package_id;
                            $model->stage = $data['stage'][$i];
                            $model->profit = $data['profit'][$i];
                            $model->created_at = date('Y-m-d H:i:s', time());
                            if (!$model->save()) {
                                $error = $model->getFirstErrors();
                                $message = '';
                                if (!empty($error)) {
                                    foreach ($error as $value) {
                                        $message .= $value;
                                    }
                                    $tmpStr = strip_tags($message);
                                    $tmpLen = mb_strlen($tmpStr);
                                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                }
                                throw new Exception("第" . ($i + 1) . "行保存失败，失败原因：{$message}");
                            } else {
                                //TODO 添加团队收益分配更新记录
                                $res = $model->setUpdateLog($model->id, $package_id, $model, $userId, PackageUpdateLog::MODULE_INCOME_DISTRIBUTION, 1);
                                if (!$res['state']) {
                                    throw new \Exception($res['msg']);
                                }

                                $status = true;
                            }
                        }
                    }
                }
                if ($status === false) {
                    $packageInitiationIncome = new PackageInitiationIncome();
                    $list = $packageInitiationIncome->getList(['package_id' => $package_id]);
                    $str = $this->renderPartial('@app/views/package/investigation/group-income.php', ['list' => $list]);
                    return Responses::response200($str, 1, '保存成功');
                    //return Responses::response400('数据未改变', true);
                }
                $transaction->commit();

                $packageInitiationIncome = new PackageInitiationIncome();
                $list = $packageInitiationIncome->getList(['package_id' => $package_id]);
                $str = $this->renderPartial('@app/views/package/investigation/group-income.php', ['list' => $list]);
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                return Responses::response200($str, 1, '保存成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

}
